﻿using System;
using System.Collections.Generic;

namespace MVVMFramework
{
    /// <summary>
    /// The class provides ability to register and retrieve any service. Modules use this class to get necessary service.
    /// </summary>
    public class ServiceManager
    {
        private readonly object syncServices;
        /// <summary>
        /// Stores the services
        /// </summary>
        private static Dictionary<Type, IService> services;

        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceManager"/> class.
        /// </summary>
        internal ServiceManager()
        {
            services = new Dictionary<Type, IService>();
            syncServices = new object();
        }

        public static readonly ServiceManager Default = new ServiceManager();

        /// <summary>
        /// Publishes the specified service type.
        /// </summary>
        /// <typeparam name="T">Type of the published service</typeparam>
        /// <param name="service">The instance of service.</param>
        public void RegisterService<T>(T service) where T : class,IService
        {
            lock (syncServices)
            {
                if (services.ContainsKey(typeof(T)))
                    throw new Exception(string.Format("Service {0} is already registered", typeof(T).FullName));

                services[typeof(T)] = service;
            }
        }

        /// <summary>
        /// Retrieves the requested service. This method returns null if the service could not be located.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T ResolveService<T>() where T : class,IService
        {
            lock (syncServices)
            {
                IService service;
                if (!services.TryGetValue(typeof(T), out service))
                    return null;
                return service as T;
            }
        }
    }
}
